﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Web;
using System.Web.Caching;
using System.Xml;
using WeChat.AspNet;

namespace TodayYongxing
{
    /// <summary>
    /// 此类定义微信服务/订阅号的首页显示内容，内容从home.xml加载过来。
    /// 首页显示内容为用户关注时显示的内容。
    /// </summary>
    public class Welcome
    {
        private const string WelcomeKey = "WelcomeKey";

        /// <summary>
        /// 从home.xml中读取多图文信息。
        /// </summary>
        public static List<Article> Articles
        {
            get
            {
                var articles = (List<Article>) HttpContext.Current.Cache[WelcomeKey];
                if (articles == null || articles.Count == 0)
                {
                    articles = new List<Article>();
                    var file = HttpContext.Current.Server.MapPath("~/weixin/home.xml");
                    var xmldoc = new XmlDocument();
                    xmldoc.Load(file);
                    var rootNode = xmldoc.DocumentElement;
                    if (rootNode != null)
                    {
                        foreach (XmlNode node in rootNode.ChildNodes)
                        {
                            var ht = new Hashtable();
                            foreach (XmlNode xn in node.ChildNodes)
                            {
                                ht.Add(xn.Name, xn.InnerText);
                            }

                            var artcile = new Article
                                {
                                    Title = (string) ht["Title"],
                                    PicUrl = (string) ht["PicUrl"],
                                    Url = (string) ht["Url"],
                                    Description = (string) ht["Description"]
                                };
                            articles.Add(artcile);
                        }
                        HttpContext.Current.Cache.Remove(WelcomeKey);
                        HttpContext.Current.Cache.Add(WelcomeKey, articles, new CacheDependency(file), DateTime.MaxValue,
                                                      TimeSpan.Zero, CacheItemPriority.BelowNormal, null);
                    }
                }
                return articles;
            }
        }
    }
}